package com.example.shopping.service.impl;

import com.example.shopping.entity.Admin;
import com.example.shopping.entity.User;
import com.example.shopping.mapper.AdminMapper;
import com.example.shopping.service.AdminService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service("adminserviceimpl")
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin login(String account, String password) {
        Admin admin = adminMapper.getUserByAccount(account);
        if(admin != null && admin.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            return admin;
        }
        return null;
    }


    @Override
    public List<User> getAllUser() {
        return  adminMapper.getAllUser();
    }

    @Override
    public List<User> getAllUserByPage(int page,int pageSize) {
        int offset = (page - 1) * pageSize;
        return adminMapper.getAllUserByPage(offset, pageSize);
    }

    @Override
    public long count() {
        return adminMapper.count();
    }


    @Override
    public boolean updateAdminPassword(String account, String oldPassword, String newPassword) {
        // 验证旧密码
        Admin admin = adminMapper.getUserByAccount(account);
        if (admin == null || !admin.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
            return false; // 旧密码不匹配
        }

        // 更新新密码
        int rows = adminMapper.updatePassword(account, DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        return rows > 0; // 返回更新是否成功
    }

}
